import Cookie from 'js-cookie'
import { apigetUserInfo } from '../api'
import Store from '../store'

// 获取右侧菜单
import { MenuList } from '../router/page'


// 获取cookie
export const getCookie = (cookieName: string = "token") => {
    return Cookie.get(cookieName)
}

// 获取用户信息
export const getUserInfo = () => {
    // 先判断token是否存在
    if (getCookie()) {
        apigetUserInfo().then(res => {
            // 先将权限字符串转化为权限数组
            const authList = res.data.auth.split(',')

            // 将用户信息保存到redux中
            Store.dispatch({ type: 'CHANGE_USER_INFO', data: res.data })

            // 将用户权限保存到redux中
            Store.dispatch({ type: 'CHANGE_AUTH_LIST', data: authList })

            // 根据权限数组 过滤 菜单 ，保存menu菜单
            const newMenu = MenuList.filter(item => {
                return authList.includes(item.auth)
            })

            // 将过滤好的菜单 保存到redux中
            Store.dispatch({ type: 'CHANGE_MENU_LIST', data: newMenu })

        })
    }
}

export const authList = (code: string) => {

    // 获取redux中的权限
    const authList = Store.getState().PublicReducer.authList

    // 判断是否有权限
    return authList.includes(code)

}